<?php

namespace App\Exports;

use App\Models\TouristVisit;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class TouristVisitsExport implements FromCollection, WithHeadings,WithMapping, WithColumnWidths, WithStyles
{
    /**
    * @return \Illuminate\Support\Collection
    */

    protected $data;
    private $rowNumber;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function collection()
    {
        return $this->data;
    }

    public function map($row): array
    {
        // 在映射方法中添加行号
        return [
            ++$this->rowNumber,
            $row->visit_ip,
            $row->visit_time,
            $row->visit_address,
            // 其他字段
        ];
    }
    public function headings(): array
    {
        return [
            ['游客访问商品记录'],
            ['序号', '访问ip', '访问时间', '访问地址'],
            // 添加更多列和副标题...
        ];
    }
    public function columnWidths(): array
    {
        return [
            'A' => 15, // 列 A 的宽度为 15
            'B' => 20, // 列 B 的宽度为 20
            'C' => 20, // 列 B 的宽度为 20
            'D' => 20, // 列 B 的宽度为 20
            // 添加其他列的宽度
        ];
    }

    public function styles(Worksheet $sheet)
    {
        // 合并单元格并添加标题
        $sheet->mergeCells('A1:D1'); // 合并第一行的A到D列

        // 设置标题样式
        $sheet->getStyle('A1')->getAlignment()->setHorizontal('center'); // 水平居中
        $sheet->getStyle('A1')->getFont()->setSize(14); // 字体大小
        $sheet->getStyle('A1')->getFont()->setBold(true); // 加粗标题文字


        $sheet->getStyle('A2:D2')->applyFromArray([
            'font' => [
                'bold' => true,
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => [
                    'rgb' => 'F2F2F2',
                ],
            ],
        ]);

        // TODO: Implement styles() method.
        // 设置所有行的行高
        $sheet->getDefaultRowDimension()->setRowHeight(20); //
        // 设置所有单元格添加线框
        $sheet->getStyle($sheet->calculateWorksheetDimension())->getBorders()->getAllBorders()->setBorderStyle('thin');

        // 设置内容垂直居中
        $sheet->getStyle($sheet->calculateWorksheetDimension())->getAlignment()->setVertical('center');
    }
}
